<?php

class McCube_Html_Form extends McCube_Html_Form_Abstract{

    protected $_values  = array();
    protected $_bundle  = null;
    protected $_tplPath = '';

    public function __construct($name, array $config=array(), $bundle=null){
        parent:: __construct($name, $config, $bundle);

        if(isset($config['method']))
            $this->setAttr('method', $config['method']);

        if(isset($config['action']))
            $this->setAttr('action', $config['action']);

        if(isset($config['protocol']) && 'AJAX' == strtoupper($config['protocol']))
            $this->setAttr('onsubmit', 'return $.form.submit(this);');
    }

    public function __toString(){
        return $this->render();
    }

    public function setTplPath($tplPath){
        $this->_tplPath = $tplPath;
        return $this;
    }

    public function sprintfAction(){
         $this->setAttr('action',
            vsprintf($this->getAttr('action'), func_get_args())
         );
         return $this;
    }

    public function start(){
        return '<form'.parent::buildAttrs().'>';
    }

    public function end(){
        return '</form>';
    }

    public function isSent(){

        /*  switch($this->_config['protocol']){
        switch($_SERVER['SERVER_PROTOCOL']){
            case 'HTTP/1.1'  :break;
        } */

        switch($this->_config['method']){
            case 'post':$container = &$_POST;break;
            case 'get' :$container = &$_GET ;break;
        }

        if(isset($container[$this->name])){
            $this->_values = $container[$this->name];
            return true;
        }
    }

    /** */
    public function render(){
        if(!empty($this->_config['userMustSeeErrors']) && $this->_errors){
             McCube_Session::getInstanceOf()->addNoticeForm(
                  'error'
                , $this->_config['label']
                , $this->_errors
            );
        }

        if(!empty($this->_config['template'])){
            return $this->_bundle->getTplEngine('form')->fetchFile(
                  $this->_tplPath.$this->name
                , array(
                    'form'=> $this
            ));
        }

        return '';
    }

}